package jvm;

import java.util.concurrent.TimeUnit;

/**
 * @author Europa
 * @create 2020-06-01 16:24
 */
public class VolatileDemo {
    //详情见单元测试

    private static int num = 0;

    private static volatile int n = 10;

    public static void main(String[] args) {
        // 可见性测试
        visible();
        invisible();
    }

    public static void invisible() {
        new Thread(() -> {
            while (num == 0) {

            }
        }).start();

        try {
            TimeUnit.SECONDS.sleep(1L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        num = 1;
        System.out.println("num = " + num);
    }

    public static void visible() {
        new Thread(() -> {
            while (n == 10) {

            }
        }).start();

        try {
            TimeUnit.SECONDS.sleep(1L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        n = 11;
        System.out.println("n = " + n);
    }
}
